<?php



namespace Home\Controller;



use Think\Controller;



class ShowsController extends Controller {

	private $access_token='';
	public function demo() {

		// 设置选项，包括URL

		$url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" . appid . "&redirect_uri=http://nuower.com/index.php/Shows/oauth&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect";
		header("Location:".$url);

	}

	public function oauth() {
		//$this->display ( "Shows/second" );exit();

		if (isset ( $_GET ['code'] )) {

			$code = $_GET ['code'];

			$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . appid . "&secret=" . appsecret . "&code=" . $code . "&grant_type=authorization_code";

			$output = https_request ( $url );

			// 第二步

			if (isset ( $output )) {

				$jsoninfo = json_decode ( $output, true );
				session(array('expire'=>$jsoninfo['expires_in']));
				session('token',$jsoninfo['access_token']);
				$url_info = "https://api.weixin.qq.com/sns/userinfo?access_token=" . $jsoninfo ['access_token'] . "&openid=" . $jsoninfo ['openid'] . "&lang=zh_CN";

				$userInfo = https_request ( $url_info );
			
			} else {

				$this->error ( "不好意思,出错了" );

			}

			// 第三步

			if (isset ( $userInfo )) {

				$res = json_decode ( $userInfo, true );

				session ( "openid", $res ['openid'] );

				session ( "nickname", $res ['nickname'] );

				$this->display ( "Shows/second" );

			} else {

				$this->error ( "不好意思,出错了" );

			}

		} else {

			$this->error ( "不好意思,出错了" );

		}

	}

	public function second() {
		$data = F ( 'data' );

		if (empty ( $data )) {

			$data = M ( 'swf_area' )->select ();

			$cache = F ( 'data', $data );

			$this->assign ( "city", $cache );

		} else {

			// dump($data);

			$this->assign ( "city", $data );

		}

		$this->display ( "second" );

	}
	
	public function third() {
			//$this->display ( "detail" );exit();
		header ( "Content-type: text/html; charset=utf-8" );
		$data = I ();	
		$jiaju = $data ['jiaju'];
		$jiajudata = explode('、',$jiaju);
		for ($i=0;$i<count($jiajudata)-1;$i++){ 
			$tmp=explode(' ', $jiajudata[$i]);
			$list[] = array(
				'name'=>$tmp[0],
				'num'=>$tmp[1],
			);
		}
		
		if(!empty($_REQUEST['shighdianti'])){  
			$startAdd=$data['startAdd']."有电梯";
		}else{
			$startAdd=$data['startAdd'].$data['shigh']."楼";	
		}
		
		if(!empty($_REQUEST['ehighdianti'])){  
			$endAdd=$data['endAdd']."有电梯";
		}else{
			$endAdd=$data['endAdd'].$data['ehigh']."楼";	
		}
			
		//添加到数据库
		$data1['getCity'] = $data['getCity'];
		$data1['startAdd'] = $startAdd;
		$data1['endAdd'] = $endAdd;
		$data1['orderno'] = $this->ordersNum ();
		$data1['ctime'] = date ( 'Y-m-d H:i:s' );
		$data1['car'] = $data['car'];
		$data1['name'] = $data['name'];
		$data1['bei1'] = $data['bei1'];
		$data1['bei2'] = $data['bei2'];
		$data1['cost'] = $data['cost'];
		$data1['costfb'] = $data['costFb'];
		$data1['car_fee'] =$data['cost']-$data['costFb'];
		$data1['time'] = $data ['appDate'] . $data ['appTime'];
		$data1['beizhu'] = $data['beizhu'];
		$data1['mphone'] = $data['mphone'];
		$data1['yphone'] = $data['yphone'];
		$data1['bag_num'] = $data['count-input'];
		$data1['jiaju_num'] = $data['jiaju'];
		$data1['ben_num'] = $data['ben'];
		$data1['distance'] = $data ['distance'];
		$data1['openid'] = $_SESSION ['openid'];
		//$data1['openid'] = 'jjjjjjjjj';
		// $data1['items'].="行李数".$data['count-input']."件<br/>大件家具：".$data['jiaju']."<br/>其他家具：".$data['ben'];
		$data1['items'].=$data['jiaju'];
		
		$res = M ( 'orders' )->data ( $data1 )->add ();

		if ($res) {
			$orderinfo = M ( 'orders' )->find($res);
			// 模板
			//$tpl = "订购单号:<span style='color:red'>" . $data ['orderno'] . "</span><br>下单时间:<span style='color:red'>" . $data ['ctime'] . "</span><br>收到来自<span style='color:red'>" . $data ["getCity"] . "</span>的订单。总金额为:<span style='color:red'>" . $data ['cost'] . "</span><br>" . "联系人:<span style='color:red'>" . $data ['name'] . "</span><br>联系电话:<span style='color:red'>" . $data ['mphone'] . "</span><br>选择车型:<span style='color:red'>" . $data ['car'] . "</span><br>" . "搬家时间:<br><span style='color:red'>" . $appDate. " " . $appTime . "</span><br>" . "起始地：<br><span style='color:red'>" . $data ['startAdd'].$shigh . "楼</span><br>目的地：<br><span style='color:red'>" . $data ['endAdd'].$ehigh . "楼</span><br>搬运物品：<span style='color:red'>".$data ['items']."</span>";
//			SendMail ( '187220366@qq.com', '亲，又来新订单了！！', $tpl );
			$this->assign ( "orderinfo", $orderinfo);
			
			$this->display ( "detail" );
			
		}else{
			$this->error ( "订单失败了！" );	
		}

	}
	
	
	

	// 订单 需要搬运

	public function orders() {

		header ( "Content-type: text/html; charset=utf-8" );

		// 解释下参数: 参数1---目标邮箱, 参数2----邮件标题,参数三--邮件正文,参数四---发件人名称;

		$data = I ();

		//dump($data);


		$data ['orderno'] = $this->ordersNum ();

		$data ['ctime'] = date ( 'Y-m-d H:i:s' );

		$data ['openid'] = $_SESSION ['openid'];

		session("name",$data ['name']);

		session("orderno",$data ['orderno']);

		unset ( $data ['options'] );

		unset ( $data ['costFb'] );

		$data ['time'] = $data ['appDate'] . $data ['appTime'];

		$appTime = $data ['appTime'];

		$appDate = $data ['appDate'];

		$shigh =  $data ['shigh'];

		$ehigh=  $data ['ehigh'];
		
		//$data['items'].="行李数".$data['count-input']."件<br/>大件家具：".$data['jiaju']."<br/>其他家具：".$data['ben'];
		$data['items'].="行李数".$data['count-input']."件<br/>大件家具：".$data['jiaju']."<br/>".$data['ben'];

		unset ( $data ['ben'] );

		unset ( $data ['appTime'] );

		unset ( $data ['appDate'] );

		unset ( $data ['shigh'] );

		unset ( $data ['ehigh'] );

		 

		$res = M ( 'orders' )->data ( $data )->add ();

		if ($res) {
			// 如果发送邮件推送成功并把信息保存到数据库并显示给用户
			// 模板
			/*$tpl = "订购单号:<span style='color:red'>" . $data ['orderno'] . "</span><br>下单时间:<span style='color:red'>" . $data ['ctime'] . "</span><br>收到来自<span style='color:red'>" . $data ["getCity"] . "</span>的订单。总金额为:<span style='color:red'>" . $data ['cost'] . "</span><br>" . "联系人:<span style='color:red'>" . $data ['name'] . "</span><br>联系电话:<span style='color:red'>" . $data ['mphone'] . "</span><br>选择车型:<span style='color:red'>" . $data ['car'] . "</span><br>" . "搬家时间:<br><span style='color:red'>" . $appDate. " " . $appTime . "</span><br>" . "起始地：<br><span style='color:red'>" . $data ['startAdd'].$shigh . "楼</span><br>目的地：<br><span style='color:red'>" . $data ['endAdd'].$ehigh . "楼</span><br>搬运物品：<span style='color:red'>".$data ['items']."</span>";

			if (SendMail ( 'wxd1277@163.com', '亲，又来新订单了！！', $tpl )) {

			} else {

				$this->error ( '订单失败了！' );

			}
			$this->assign ( "tpl", $tpl );
			$this->display ( "detail" );*/
			$this->success ( "订单提交成功" );

		} else {

			$this->error ( "订单失败了！" );

		}

		

	}

	// 取消订单

	public function delOrder() {

		$data ['openid'] = $_SESSION ['openid'];

		$name = $_SESSION['name'];

		$ordNo = $_SESSION['orderno'];

		$tpl = $name."(".$_SESSION['nickname'].")"."取消订单了"."单号为:". $ordNo;

		 

		$where = array (

				"openid" => $data ['openid'] ,

				"orderno" => $ordNo

		);

		//-1代表以删除订单

		$status['status'] = '-1';

		$res = M ( 'orders' )->where ( $where )->save($status);; // 删除用户数据

		if ($res) {

			if (SendMail ( 'nuowoer@163.com', '亲，有人取消订单了！', $tpl )) {

				$this->success("取消订单成功！",U ( 'Show/index' ));

			} else {

				$this->error ( "取消订单失败",U ( 'Show/index' ) );

			}

		} else {

			$this->error ( "取消订单失败",U ( 'Show/index' ) );

		}

	}

	// 单号

	public function ordersNum() {

		$data = date ( 'Ymd' );

		$whe = "%" . $data . '%';

		$where ['orderno'] = array (

				'like',

				$whe

		);

		$res = M ( 'orders' )->where ( $where )->order ( 'id desc' )->getField ( 'orderno' );

		// 如果存在

		if ($res) {

			$order = substr ( $res, - 4 ) + 1;

			$orderNo = 'C' . $data . sprintf ( "%04d", $order ); // 生成4位数，不足前面补0

		} else {

			// 否则单号就是0001

			$orderNo = 'C' . $data . "0001";

		}

		return $orderNo;

	}

	public function saveorder()
	{
		$orderid=I('get.id');
		$map['id']=$orderid;
		$save['paystatus']=1;
		$save['paytype']='wx';
		$q=M('orders')->where($map)->save($save);
		$this->sendtpl_msg('oB_KewRQprjKA4ETYbqcRQgMiBk0',$orderid,'小型搬家需要搬运订单已支付');
		//$this->sendtpl_msg('oB_KewXjx0kMThvx12moge3K9n8k',$orderid,'小型搬家需要搬运订单已支付');
		if ($q) {
			$this->redirect('Remind/success');
		}
	}


	

	/**

	 * 需要搬运的算法

	 * $Fc车费 

	 */

	public function banYun() {

		header ( "Content-type: text/html; charset=utf-8" );

		$dst = $_POST ['dst'];

		$Fb = $_POST ['fb'];
		
		//$res = substr ( $dst, 0, strlen ( $dst ) - 6 );

		$car = $_POST ['car'];

		// 调用计算车费函数

		$Fc = $this->carCost ( $dst, $car );

		$F = $Fc+$Fb;

		echo $F.'|'.$Fc;

	}

	/**

	 * *

	 * 车费计算公式

	 * $res距离,$car车型

	 *

	 * *

	 */

	private function carCost($res, $car) {

		switch ($car) {

			case "面包车" :

				// 起步价

				$Fa = 35;

				if ($res > 5) {

					$cost = round(35 + ($res - 5) * 4);

				} else {

					$cost = 35;

				}

				break;

			case "小型平板货车" :

				// 起步价

				$Fa = 50;

				if ($res > 5) {

					$cost = round($Fa+ ($res - 5) * 5);

				} else {

					$cost = $Fa;

				}

				break;

			case "中型平板货车" :

				// 起步价

				$Fa = 80;

				if ($res > 5) {

					$cost = round(80 + ($res - 5) * 5);

				} else {

					$cost = 80;

				}

				break;

			case "中型厢式货车" :

				// 起步价

				$Fa = 100;

				if ($res > 5) {

					$cost = round(100 + ($res - 5) * 5);

				} else {

					$cost = 100;

				}

				break;

			default :

				// 起步价

				$Fa = 35;

				if ($res > 5) {

					$cost = round(35 + ($res - 5) * 4);

				} else {

					$cost = 35;

				}

				break;

		}

		return $cost;

	}


	//发送模板消息
	public function sendtpl_msg($touser,$id,$first=''){

    $this->access_token=$this->getToken();
	$orderinfo=M('orders')->find($id);
	$orderno=$orderinfo['orderno'];
	$cost=$orderinfo['cost'];
//模板消息	
$template=array(
'touser'=>$touser,
'template_id'=>"85vh2nUY5d0pGOYKdnqnY3_AjIWf8PO9c-RZSCWORUM",
'url'=>"http://nuower.com/index.php/shows/showadmin/id/".$id,
'topcolor'=>"#7B68EE",
'data'=>array(
'first'=>array('value'=>urlencode($first),'color'=>"#743A3A"),
'keyword1'=>array('value'=>urlencode($orderinfo['name']),'color'=>'#743A3A'),
'keyword2'=>array('value'=>urlencode($orderinfo['mphone']),'color'=>'#743A3A'),
'keyword3'=>array('value'=>urlencode('小型搬家需要搬运'),'color'=>'#743A3A'),
'keyword4'=>array('value'=>urlencode($orderinfo['time']),'color'=>'#743A3A'),
'keyword5'=>array('value'=>urlencode($orderinfo['items']),'color'=>'#743A3A'),
'remark'=>array('value'=>urlencode('请及时审核'),'color'=>'#743A3A'),
)
);

$cus_user=$orderinfo['openid'];

	$content='挪窝儿已经收到您的预约，正在努力匹配靠谱搬家师傅，请耐心等待。需要查看或取消订单，请点击“我的”>“我的订单”。
《相关费用说明》
1.请准确描述您的物品详情，现场情况与描述不符的，费用按照实际数量输入平台显示的价格结算。
2.报价不包含过路过桥费，面包车走海底隧道加收费用20元，货车走跨海大桥加收费用150元。
3.报价不包含家具拆装费，如需拆装请与师傅协商价格。
4.楼层1楼从平地算起，楼底商业网点没有被计算的，每层网点加收费用10元。
5.车辆不能停靠到单元门口20米范围内的，超过20米的部分按照 2元/米收取平移费，具体距离和附加费用请现场与师傅协商。
6.搬家路线及里程以高德地图提供的两地最短行车距离为准。';

$data = '{
        "touser":"'.$cus_user.'",
        "msgtype":"text",
        "text":
        {
             "content":"'.$content.'"
        }
    }';


$json_template=json_encode($template);

$url="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$this->access_token;

$url2 = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$this->access_token;
$res=http_request($url,urldecode($json_template));
$res2=https_post($url2,urldecode($data));

return;
}

public function submit_order()
{	//oB_KewRQprjKA4ETYbqcRQgMiBk0
	$id=I('post.id');
	if (empty($id)) {
		$this->error('缺少参数');
	}else{
	$data['id']=$id;
	$data['status']=1;
	M('orders')->save($data);
	$this->sendtpl_msg('oB_KewRQprjKA4ETYbqcRQgMiBk0',$id,'管理员，你好，有一个顾客预约了您的服务，请注意安排时间。');
	//$this->sendtpl_msg('oB_KewXjx0kMThvx12moge3K9n8k',$id,'管理员，你好，有一个顾客预约了您的服务，请注意安排时间。');
	$this->success('提交成功。等待反馈',U('Shows/second'));
	}
	

}




public function showadmin()
{	
	$id=I('get.id');
	$data=M('orders')->find($id);

	$tpl = "订购单号:<span style='color:red'>" . $data ['orderno'] . "</span><br>下单时间:<span style='color:red'>" . $data ['ctime'] . "</span><br>联系人:<span style='color:red'>" . $data ['name'] . "</span><br>联系电话:<span style='color:red'>" . $data ['mphone'] . "</span><br>起始地：<span style='color:red'>" . $data ['startadd'] . "</span><br>目的地：<span style='color:red'>" . $data ['endadd'] . "</span>搬家时间:<br><span style='color:red'>" .$data['time']. "</span><br>行李件数：<span style='color:red'>". $data ['bag_num'] ."</span><br>
	物品详情:<span style='color:red'>". $data ['items'] ."</span><br>备注:<span style='color:red'>" . $data ['beizhu']."</span><br>选择车型:<span style='color:red'>" . $data ['car'] . "</span><br>总金额为:<span style='color:red'>" . $data ['cost'] . "</span>";
$this->assign('tpl',$tpl);
	$this->display();
}
	



	//发送客服消息
function _reply_customer($touser,$content){
    
    $ACC_TOKEN=$this->getToken();
    
    $data = '{
        "touser":"'.$touser.'",
        "msgtype":"text",
        "text":
        {
             "content":"'.$content.'"
        }
    }';
    
    $url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$ACC_TOKEN;
    
    $result = https_post($url,$data);
    $final = json_decode($result);
    return $final;
}

public function getToken()
{	
	$data = json_decode(get_php_file("access_token.php"));
	$now=time();
    if ($data->expire_time <$now ) {
       $json_token=http_request("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".appid."&secret=".appsecret);
$access_token=json_decode($json_token,true);
//获得access_token
$f_access_token=$access_token['access_token'];
      if ($f_access_token) {
        $data->expire_time = time() + 7000;
        $data->access_token = $f_access_token;
      set_php_file("access_token.php", json_encode($data));
      }
    } else {

     $f_access_token = $data->access_token;
    }
    return $f_access_token;
}

}



?>